<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-button type='primary' @click='RolesdialogVisible=true'>添加角色</el-button>
      <!-- 表格部分 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 栅格布局 -->
            <el-row :class="['bdBottom',i1===0 ? 'bdTop' : '','vCenter']" v-for="(item1,i1) in scope.row.children"
              :key="item1.children.id">
              <!-- 一级权限 -->
              <el-col :span='5'>
                <el-tag closable @close="removeRightInfo(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和三级权限 -->
              <el-col :span='19'>
                <!-- 通过for循环 嵌套渲染二级权限 -->
                <el-row :class="[i2 === 0 ?'':'bdTop','vCenter']" v-for="(item2,i2) in item1.children"
                  :key="item2.children.id">
                  <el-col :span='6'>
                    <el-tag type="success" closable @close="removeRightInfo(scope.row,item2.id)">{{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span='18'>
                    <el-tag type='warning' v-for="(item3) in item2.children" :key="item3.id" closable
                      @close="removeRightInfo(scope.row,item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
                <el-row></el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="320px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editDialog(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeUserById(scope.row.id)">删除
            </el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色的弹出框 -->
    <el-dialog title="添加角色" :visible.sync="RolesdialogVisible" width="50%" @close="addDialogClosed">
      <el-form :model="addRoles" :rules='addRolesRules' ref="addRolesRef" label-width='70px'>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="RolesdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色的对话框 -->
    <el-dialog title="编辑角色" :visible.sync="EditdialogVisible" width="50%" @close="editFormClosed">
      <el-form :model="editForm" :rules='editFormRules' ref="editFormRef" label-width='70px'>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限的对话框 -->
    <el-dialog title="提示" :visible.sync="setRightDialogVisible" width="50%" @close="setClosed">
      <!-- 树形控件 -->
      <el-tree :data="rightList" :props="TreeProps" show-checkbox node-key='id' default-expand-all :default-checked-keys="defaultKeys" ref='treeRef'></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        rolesList: [],
        // 添加角色的弹框显示与隐藏
        RolesdialogVisible: false,
        // 添加角色列表
        addRoles: {
          roleName: '',
          roleDesc: ''
        },
        // 添加角色的验证规则
        addRolesRules: {
          roleName: [{
            required: true,
            message: '不能为空',
            trigger: 'blur'
          }]
        },
        EditdialogVisible: false,
        // 根据id 将查询到的数据放在这里
        editForm: [],
        // 编辑角色的校验规则
        editFormRules: {
          roleName: [{
            required: true,
            message: '不能为空',
            trigger: 'blur'
          }],
          roleDesc: [{
            required: true,
            message: '不能为空',
            trigger: 'blur'
          }]
        },
        // 分配权限对话框的展开与收起
        setRightDialogVisible:false,
        // 权限列表
        rightList:[],
        TreeProps:{
          label:'authName',
          children:'children'
        },
        // 默认选中的节点的id
        defaultKeys:[105,116],
        // 角色id
        roleId:''
      }
    },
    created() {
      this.getRolesList()
    },
    methods: {
      async getRolesList() {
        const {
          data: res
        } = await this.$http.get('roles')

        if (res.meta.status !== 200) {
          return this.$message.error('获取角色列表失败')
        }
        this.rolesList = res.data

        console.log(this.rolesList);
      },
      //   监听对话框关闭事件
      addDialogClosed() {
        //   表单内容进行重置
        this.$refs.addRolesRef.resetFields();
      },
      // 添加用户的确定按钮  
      addRole() {
        //   表单预验证
        this.$refs.addRolesRef.validate(async valid => {
          if (!valid) return;
          // 验证成功 就可以发起添加用户的请求操作
          const {
            data: res
          } = await this.$http.post('roles', this.addRoles)

          if (res.meta.status !== 201) {
            return this.$message.error("添加角色失败")
          }
          this.$message.success('添加角色成功')
          // 隐藏添加的提示框
          this.RolesdialogVisible = false
          // 重新获取数据
          this.getRolesList()
        })
      },
      async editDialog(id) {
        console.log(id)
        const {
          data: res
        } = await this.$http.get('roles/' + id)
        if (res.meta.status !== 200) return this.$message.error('获取失败')
        this.editForm = res.data
        this.EditdialogVisible = true
      },
      editFormClosed() {
        this.$refs.editFormRef.resetFields();
      },
      //   编辑表单后 预验证并提交
      editRolesInfo() {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) return;
          // 数据校验成功后，对数据进行存储
          const {
            data: res
          } = await this.$http.put('roles/' + this.editForm.roleId, {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc
          })
          if (res.meta.status !== 200) {
            return this.$message.error("数据更新失败")
          }
          this.$message.success("数据更新成功")
          this.EditdialogVisible = false
          this.getRolesList()
        })
      },
      //   删除角色
      async removeUserById(id) {
        //   点击删除后的提示框
        const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          // catch 捕获取消的信息
        }).catch(err => err)
        // 弹框点击取消  confirmResult = 字符串 cancel
        // 弹框点击确认  confirmResult = 字符串 confirm
        if (confirmResult !== 'confirm') {
          return this.$message.info('已取消删除')
        }
        // 删除操作
        const {
          data: res
        } = await this.$http.delete('roles/' + id)

        if (res.meta.status !== 200) return this.$message.error('删除用户失败')
        this.$message.success('删除用户成功')
        this.getRolesList()
      },
      async removeRightInfo(roles, id) {
        // 提示是否删除的弹框
        const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (confirmResult !== 'confirm') {
          return this.$message.info('已取消了删除')
        }
        // 删除操作
        const {
          data: res
        } = await this.$http.delete('roles/' + roles.id + '/rights/' + id)
        if (res.meta.status !== 200) {
          return this.$message.error('删除失败')
        }
        this.$message.success('删除成功')
        roles.children = res.data
      },
      // 展开分配权限
      async showSetRightDialog(role) {
        this.roleId=role.id
        // 获取所有的权限
        const {data:res} = await this.$http.get('rights/tree')
        if(res.meta.status !== 200){
          return this.$message.error('获取权限失败')
        }
        this.rightList=res.data
        
        this.getLeafKeys(role,this.defaultKeys)

        this.setRightDialogVisible = true
      },
      // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
      getLeafKeys(node,arr){
        // 如果当前 node 节点不包含children 属性，则是三级节点
        if(!node.children){
          return arr.push(node.id)
        }
        node.children.forEach(item => this.getLeafKeys(item,arr))
      },
      // 监听分配权限对话框的关闭事件
      setClosed(){
        this.defaultKeys=[];
      },
      // 点击为角色分配权限
      async allotRights(){
        const keys= [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys(),
        ];
        const keyStr=keys.join(',')
        const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{
          rids:keyStr
        })

        if(res.meta.status!==200){
          return this.$message.error('分配权限失败')
        }
        this.$message.success('分配权限成功')
        this.getRolesList();
        this.setRightDialogVisible=false
      }
    }
  }

</script>

<style lang="less" scoped>
  .el-tag {
    margin: 10px;
  }

  .bdTop {
    border-top: 1px solid #eee;
  }

  .bdBottom {
    border-bottom: 1px solid #eee;
  }

  // 纵向居中
  .vCenter {
    display: flex;
    align-items: center;
  }

</style>
